/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.google.code.twiddling.core.command;

import java.io.PrintWriter;

import com.google.code.twiddling.core.clp.Option;
import com.google.code.twiddling.core.exception.TwiddlingException;
import com.google.code.twiddling.core.util.DocUtil;


/**
 * 
 * @author <a href="mailto:jeff.yuchang@gmail.com">Jeff Yu</a>
 *
 */
public abstract class AbstractCommand implements ICommand {
	
	@Option(name="-h", aliases={"--help"}, description="display help message")
	private boolean help;
	
	@Option(name="-v", aliases={"--verbose"}, description="output the result in verbose mode, include error stack if it has")
	private boolean verbose;
	
	public boolean isHelp() {
		return help;
	}

	public void setHelp(boolean help) {
		this.help = help;
	}

	public boolean isVerbose() {
		return verbose;
	}

	public void setVerbose(boolean verbose) {
		this.verbose = verbose;
	}

	public final void execute(CommandContext context) throws Exception {
		if (help) {
			displayHelp(context);
		} else {
			doExecute(context);
		}
	}
	
	public void displayHelp(CommandContext context) throws TwiddlingException {
		PrintWriter out = context.getIO().getOut();
		ICommand command = context.getCommand();
		DocUtil.renderToConsole(command.getClass(), out);
	}
	
	
	public abstract void doExecute(CommandContext context) throws Exception;

}
